Imports System.Drawing.Printing

Public Class wxPrinter

    Private mSciEdit As New SCI_EDIT
    Private mprintFont As Font
    Private mLineCount As Int32

    Dim pd As New PrintDocument


    Public Sub New()
        AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
    End Sub

    Public Sub Preview(ByVal Sciedit As SCI_EDIT)

        Try
            Dim mPreview As New PrintPreviewDialog

            mLineCount = 0
            mSciEdit = Sciedit
            mprintFont = New Font(mSciEdit.Font.Name, mSciEdit.Font.Size)

            mPreview.Document = pd
            mPreview.Show()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Public Sub Print(ByVal Sciedit As SCI_EDIT)

        Try
            mLineCount = 0
            mSciEdit = Sciedit
            mprintFont = New Font(mSciEdit.Font.Name, mSciEdit.Font.Size)

            Dim mPrinterDialog As New PrintDialog
            mPrinterDialog.Document = pd

            If Not (mPrinterDialog.ShowDialog() = DialogResult.OK) Then
                Exit Sub
            End If

            pd.Print()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub


    Private Function SciEditReadLine() As String

        If mLineCount < mSciEdit.GetLineCount Then
            Dim tempLine As String = mSciEdit.GetLine(mLineCount)
            mLineCount += 1
            Return tempLine
        Else
            Return vbNullString
        End If

    End Function


    ' The PrintPage event is raised for each page to be printed.
    Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
        Dim linesPerPage As Single = 0
        Dim yPos As Single = 0
        Dim count As Integer = 0
        Dim leftMargin As Single = ev.MarginBounds.Left
        Dim topMargin As Single = ev.MarginBounds.Top
        Dim line As String = Nothing

        ' Calculate the number of lines per page.
        linesPerPage = ev.MarginBounds.Height / mprintFont.GetHeight(ev.Graphics)

        ' Print each line of the file.
        While count < linesPerPage
            line = SciEditReadLine()
            If line Is vbNullString Then
                Exit While
            End If
            yPos = topMargin + count * mprintFont.GetHeight(ev.Graphics)
            ev.Graphics.DrawString(line, mprintFont, Brushes.Black, leftMargin, yPos, New StringFormat)
            count += 1
        End While

        ' If more lines exist, print another page.
        If Not (line Is vbNullString) Then
            ev.HasMorePages = True
        Else
            ev.HasMorePages = False
        End If

    End Sub


End Class
